package com.example.demo555.common;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.ThreadMXBean;

public class JvmUtil {

    private static final Runtime runtime = Runtime.getRuntime();

    private static final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

    private static final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    private JvmUtil() {

    }

    /**
     * @return 返回可用于java虚拟机的处理器数量
     */
    public static int availableProcessors() {
        return runtime.availableProcessors();
    }

    /**
     * @return 返回java虚拟机中的内存总量
     */
    public static long totalMemory() {
        return convertByteToMegabyte(runtime.totalMemory());
    }

    /**
     * @return 返回java虚拟机尝试使用的最大内存量
     */
    public static long maxMemory() {
        return convertByteToMegabyte(runtime.maxMemory());
    }

    /**
     * @return 返回用于对象分配的堆的内存量
     */
    public static long heapMemoryUsage() {
        return convertByteToMegabyte(memoryMXBean.getHeapMemoryUsage().getUsed());
    }

    /**
     * @return 返回当前线程数
     */
    public static int threadCount() {
        return threadMXBean.getThreadCount();
    }

    /**
     * 将字节转换为兆字节
     * @param bytes 字节数
     * @return 兆字节数
     */
    public static long convertByteToMegabyte(long bytes) {
        return bytes / 1024 / 1024;
    }
}
